<template>
  <!--修改标题-->
  <el-row :gutter="20">
    <el-col :span="12">
      <el-input v-model="subCols.title" placeholder="" size="mini"></el-input>
    </el-col>
    <el-col :span="12">
      <el-button type="" @click="del" size="mini" >删除分栏</el-button>
    </el-col>
  </el-row>
  <!--操作，全选，删除-->
  <div>
    <el-checkbox
      v-model="checkAll"
      :indeterminate="isIndeterminate"
    >全选</el-checkbox>
  </div>
  <!--显示表单控件的字段，设置关联关系-->
  <el-checkbox-group
    v-model="checkValue2"
    size="mini"
  >
    <el-checkbox style="width: 80px;"
      v-for="(item, index) in colOrder"
      :key="index"
      :label="item"
      :disabled="!canCheck[item]"
    >
      {{itemMeta[item].label}}
    </el-checkbox>
  </el-checkbox-group>
</template>

<script>
  import { reactive, computed, watch, ref } from 'vue'

</script>


<script setup>

  const props = defineProps({
    formMeta: Object, // 表单的 meta
    title: String, // 栏目名称
    subIndex: Number, // 栏目的序号
    subCols: Object // 当前分栏的信息
  })

  const subCols = props.subCols

  const { itemMeta, subs, colOrder } = props.formMeta

  // 传递 选择的字段
  const checkValue2 = computed({
    set: (val) => {
      props.subCols.colIds.length = 0
      if (val) {
        // 全选
        props.subCols.colIds.push(...val)
      }
    },
    get: () => {
      return props.subCols.colIds
    }
  })

  // 设置全选
  const isIndeterminate = ref(false)
  const checkAll = computed({
    set: (val) => {
      props.subCols.colIds.length = 0
      if (val) {
        // 全选
        colOrder.forEach(id => {
          if (canCheck[id])
            props.subCols.colIds.push(id)
        })
      }
    },
    get: () => {
      const re = props.subCols.colIds.length === colOrder.length
      if (re) {
        isIndeterminate.value = false
      } else {
        if (props.subCols.colIds.length > 0) 
          isIndeterminate.value = true
      }
      return re
    }
  })

  // 设置其他栏目的字段不能选
  const canCheck = reactive({})
  
  let timeout = null
  watch(subs, () => {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      // 先都设置为可用
      for(const key in itemMeta) {
        canCheck[key] = true
      }
      // 再设置为不可用
      subs.cols.forEach(sub => {
        if (sub.title !== props.title) {
          sub.colIds.forEach(id => {
            canCheck[id] = false
          })
        }
      })
    }, 100)

  },{immediate:true})

</script>